#include <raylib.h>
#include <stdbool.h>
#include <complex.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>

#define _OUTPUT_FILE "outpng/Julia.png"
#ifndef __IMAGE_OUT_OFF__
#define STB_IMAGE_IMPLEMENTATION
#include "include/stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "include/stb_image_write.h"
#endif

#ifndef __IMAGE_OUT_OFF__
    typedef struct {
        int w,h,ch;
        unsigned char *data;
    }__out_image;
#endif

int n = 30;
double complex nn = 2.0;
complex double c = 0;
complex double z = 0;
bool ok = true;
complex double fc[30] = {0};
int mx[4000][4000] = {0};

//复平面坐标转换屏幕坐标
Vector2 real_to_mpos(complex double val){
    double x = creal(val);
    double y = cimag(val);
    int px = (x-(-2.0))/0.001;
    int py = (y-(-2.0))/0.001;
    return (Vector2){px,py};
}

int main(int argc,char **argv){
    if(argc<5){
        c = 0.156*I-0.8;
    }else {
        int o='0';
        double img=0.0,rea=0.0;
        while ((o=getopt(argc,argv,"r:i:n:")) != -1) {
            switch (o) {
                case 'r': rea = atof(optarg); break;

                case 'i': img = atof(optarg); break;

                case 'n': nn = atoi(optarg); break;
            }
        }
        // printf("r:%lf,i:%lf\n",rea,img);
        c = rea + img *I;
    }
    //计算某点是否满足该集合
    for (double i = -2.0;i < 2.0;i+=0.001){
        for (double ii=-2.0;ii < 2.0;ii+=0.001){
            // fc[0] = 0;
            ok = true;
            fc[0] = i + ii*I;
            for (int j=0;j<(n-1);j++){
                fc[j+1] = cpow(fc[j], nn) + c;
                if(cabs(fc[j+1])>2.0){
                    ok = false;
                    break;
                }
            }
            if(ok){
                Vector2 npos = real_to_mpos(i+ii*I);
                mx[(int)npos.x][(int)npos.y] += 1;
            }/*else{
                printf("not the %lf %lf\n",i,ii);
            }*/
        }
    }
#ifndef __IMAGE_OUT_OFF__
    bool writed = false;
    __out_image imgo = (__out_image){.w = 4000,.h=4000,.ch=1,.data = (unsigned char*)calloc(4000*4000*1,1)};
#endif
    //绘制
    InitWindow(4000, 4000, "hello");
    SetTargetFPS(30);
    while (!WindowShouldClose()) {
        BeginDrawing();
        ClearBackground(WHITE);
        for (int i =0;i<4000 ;i++ ) {
            for (int j=0;j<4000 ; j++){
                if (mx[i][j]!=0){
#ifndef __IMAGE_OUT_OFF__
                    // if(writed == false){
                    imgo.data[(j)*imgo.w+(i)]=255;
//                         writed = true;
//                     }
#endif
                    DrawPixel(i,j , BLACK);
                }
            }
        }
        EndDrawing();
    }
#ifndef __IMAGE_OUT_OFF__
    stbi_write_png(_OUTPUT_FILE, imgo.w, imgo.h, imgo.ch, imgo.data, imgo.w *imgo.ch);
    free(imgo.data);
#endif
    CloseWindow();
}
